<script lang="ts" setup>
import { ref, computed } from 'vue';
import dayjs from 'dayjs';
import API from "@/service/api/order";
import { requestToast } from "@/utils/requestToast";
import { useRouter } from 'vue-router';
import { truncateText } from "@/utils/ellipsis";
import { useStore } from '@/stores/user';
import { someFieldStore } from "@/stores/somefield";

const props = defineProps<{
    item: any;
}>();

// 按钮配置项类型
interface ButtonConfig {
    show: boolean;
    text: string;
    action?: () => void;
    props: Record<string, any>;
}


// 计算属性：动态生成按钮配置
const mButtonConfigs = computed<ButtonConfig[]>(() => {
    const record = props.item;
    if (!record) return [];

    return [
        // 催单按钮
        {
            show: record.is_urgent === 0 && record.handle_status === 'wait',
            text: '催单',
            action: () => clkUrgeOrder(record.order_num),
            props: {
                iLinearGradien: true,
                iColor: '#FFFFFF',
                hairline: false,
                disabled: false,
            }
        },
        // 处理中按钮
        {
            show: record.handle_status === 'processing',
            text: '处理中',
            props: {
                iLinearGradien: true,
                iColor: '#FFFFFF',
                hairline: true,
                disabled: true,
            }
        },
        // 已催办按钮
        {
            show: record.is_urgent === 1 && record.handle_status === 'wait',
            text: '已催办',
            props: {
                iLinearGradien: true,
                iColor: '#FFFFFF',
                hairline: true,
                disabled: true,
            }
        },
        // 待评价按钮
        {
            show: record.is_appraise === 0 && record.handle_status === 'finish',
            text: '待评价',
            action: clkEvaluation,
            props: {
                iLinearGradien: true,
                iColor: '#FFFFFF',
                hairline: false,
                disabled: false,
            }
        },
        // 已评价按钮
        {
            show: record.is_appraise === 1 && record.handle_status === 'finish',
            text: '已评价',
            props: {
                iLinearGradien: true,
                iColor: '#FFFFFF',
                hairline: true,
                disabled: true,
            }
        }
    ];
});

const mRouter = useRouter();

const clkImagePreview = (url: string) => {
    // 收集所有part中的图片
    const allImages = props.item.order_parts.reduce((images: any, part: { part_type: number; pic_value: any; }) => {
        if (part.part_type === 3 && Array.isArray(part.pic_value)) {
            return [...images, ...part.pic_value];
        }
        return images;
    }, [] as string[]);

    showImagePreview(allImages);
};

// 催单点击事件
const emit = defineEmits<{
    (e: 'is-Urgent'): void;
    (e: 'is-Appraise'): void;
}>();

const clkUrgeOrder = async (order_num: string) => {
    const { status } = await requestToast({ order_num: order_num }, API.orderUrgent, "你的催办已收到，专属客服加急处理中！")
    if (status) {
        emit('is-Urgent')
    }
};

//评价点击事件
const mEvaluateRef = ref();
const clkEvaluation = async () => {
    mEvaluateRef.value.openDialog();
};

const get24hLater = (time: string) => {
    return dayjs(time).add(24, 'hour').format('YYYY-MM-DD HH:mm:ss');
};

const clkBeforeClose = () => {
    mEvaluateRef.value.closeDialog();
    emit('is-Appraise')
};

//未登录没有详情
const mUser = useStore();
const mSomefield = someFieldStore();
const clkJumpToDetail = (order_num: string) => {
    if (mUser.state || mSomefield.order_num != "") {
        mRouter.push({
            path: '/order_detail',
            query: { order_num: order_num },
        });
    }
}

const clkGetStatusMessage = (item: { handle_status: any; apply_time: string; is_appraise: number; order_status: string; }) => {
    switch (item.handle_status) {
        case 'wait':
            return `你提交的工单已受理，预计将在${get24hLater(item.apply_time)}前告知你处理结果。`;
        case 'processing':
            if (item.order_status == 'waitFurther') {
                return '你的专属客服给你发送了一条消息，请注意查收...';
            }
            return '你的专属客服正在加紧处理中...';
        case 'finish':
            return item.is_appraise === 0
                ? '你的服务工单已处理完成，你可对该结果进行服务评价。'
                : '你的服务工单已处理完成。';
        default:
            return '';
    }
};

// 计算属性：获取第一张图片和总剩余数量
const firstImageData = computed(() => {
    // 找到第一个包含图片的part
    const firstImagePart = props.item.order_parts.find((part: { part_type: number; pic_value: string | any[]; }) => part.part_type === 3 && part.pic_value?.length > 0);
    if (!firstImagePart) return { firstImage: null, remainingCount: 0 };

    // 计算所有part中的图片总数
    const totalImages = props.item.order_parts.reduce((total: any, part: { part_type: number; pic_value: string | any[]; }) => {
        if (part.part_type === 3 && Array.isArray(part.pic_value)) {
            return total + part.pic_value.length;
        }
        return total;
    }, 0);

    // 剩余图片数量 = 总数 - 1（第一张）
    const remainingCount = totalImages > 0 ? totalImages : 0;

    return {
        firstImage: firstImagePart.pic_value[0],
        remainingCount
    };
});

</script>
<template>
    <div>
        <div class="gr-list" @click="clkJumpToDetail(item.order_num)" >
            <cVanrow justify="space-between" align="center" class="gr-list-row">
                <cVncol class="text-[24px] font-medium">工单号：{{ item.order_num }}</cVncol>
                <cVncol>
                    <cButton v-for="(btn, index) in mButtonConfigs" :key="index" v-show="btn.show && mUser.state"
                        class="w-[164px]" :iLinearGradien="btn.props.iLinearGradien" :iColor="btn.props.iColor"
                        :disabled="btn.props.disabled" iHeight="7.422vmin" iFontSize="3.646vmin" round
                        @click.stop="btn.action?.()">
                        {{ btn.text }}
                    </cButton>
                </cVncol>
            </cVanrow>
            <ul class="gr-list-ul">
                <div class="flex items-center m-b-[15px]">
                    <li v-if="firstImageData.firstImage">
                        <div class="gr-list-image">
                            <lazy-component>
                                <div class="image-container m-r-[15px]">
                                    <van-image :src="`${firstImageData.firstImage}?x-oss-process=image/resize,p_30`"
                                        width="19.792vmin" height="19.792vmin" lazy-load fit="cover"
                                        class="overflow-hidden border-rd-[24px]"
                                        @click.stop="clkImagePreview(firstImageData.firstImage)"></van-image>
                                    <span v-if="firstImageData.remainingCount > 0"
                                        class="image-count color-white text-[20px]">
                                        <van-icon name="photo-o" color="white" />
                                        {{ firstImageData.remainingCount }}
                                    </span>
                                </div>
                            </lazy-component>
                        </div>
                    </li>
                    <div class="gr-order-right flex-1 m-l-[10px]">
                        <h1 class="text-[32px] font-medium">{{ item.work_order_template_name }}</h1>
                        <p class="text-[24px] color-[#3D3D3D]/80">{{ truncateText(item.detail, 18) }}</p>
                        <div class="gr-gameinfo">
                            <span v-show="item.game_name != ''"
                                class="text-[20px] font-medium color-[#EB731D] bg-[#EB731D]/10 p-[5px] m-r-[10px] rounded-[5px]">{{
                                    item.game_name }}</span>
                            <span v-show="item.server_name != ''"
                                class="text-[20px] font-medium color-[#EB731D] bg-[#EB731D]/10 p-[5px] m-r-[10px] rounded-[5px]">{{
                                    item.server_name }}</span>
                            <span v-show="item.role_name != ''"
                                class="text-[20px] font-medium color-[#EB731D] bg-[#EB731D]/10 p-[5px] m-r-[10px] rounded-[5px]">{{
                                    item.role_name }}</span>
                        </div>
                    </div>
                </div>
                <li class="gr-progress items-center">
                    <span class="color-[#3D3D3D] font-bold min-w-[100px] m-r-[15px]">
                        {{ item.handle_status_name }}
                    </span>
                    <span class="status-message m-l-[10px] text-[#3D3D3D]/80 text-[24px] font-medium">
                        {{ clkGetStatusMessage(item) }}
                    </span>
                </li>
            </ul>
        </div>
        <cEvaluate ref="mEvaluateRef" @is-Confirm="clkBeforeClose" :orderData="props.item"></cEvaluate>
    </div>
</template>

<style lang="scss" scoped>
.gr-list {
    background: white;
    padding: 0px 0px 10px 0px;
    border-radius: 24px;
    border: none;
    margin-bottom: 20px;
    .gr-list-row {
        padding: 23px;
        border-bottom: 1px solid rgba(61, 61, 61, 0.1);
    }

    .gr-list-ul {
        margin-top: 15px;
        font-size: calc($fontSize + 9px);
        padding: 13px 23px 23px 23px;

        .gr-list-image {
            .image-container {
                position: relative;

                .image-count {
                    background: hsla(0, 0%, 0%, 0.3);
                    position: absolute;
                    padding: 1px 3px 1px 3px;
                    border-radius: 5px;
                    top: 10px;
                    right: 10px;
                    line-height:2px;
                }
            }
        }

        .gr-progress {
            display: flex;
            margin-top: 10px;
            background: #F6F9FB;
            border-radius: 24px;
            font-size: calc($fontSize + 7px);
            padding: 20px 20px 20px 20px;
        }
    }
}
</style>